from flask import render_template, current_app, session, request, jsonify, g

from info import constants
from info.models import User, News, Category
from info.utils import response_code
from info.utils.common import user_login_data
from . import index_blueprint


@index_blueprint.route("/")
@user_login_data
def index():
    user = g.user

    # 查询点击排行信息
    host_news_object = None
    try:
        host_news_object = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
    host_news_dict = [new.to_basic_dict() for new in host_news_object]

    # 首页显示分类菜单
    categories = Category.query.all()
    categories_dicts = []
    for category in enumerate(categories):
        # print(category)
        # 拼接内容
        categories_dicts.append(category[1].to_dict())

    data = {
        "user_info": user.to_dict() if user else None,
        "host_news_dict": host_news_dict,
        "categories_dicts": categories_dicts
    }
    return render_template("news/index.html", data=data)


@index_blueprint.route("/favicon.ico")
def icon():
    return current_app.send_static_file("news/favicon.ico")


@index_blueprint.route("/newslist")
def get_news_list():
    """
        获取指定分类的新闻列表
        1. 获取参数
        2. 校验参数
        3. 查询数据
        4. 返回数据
        :return:
    """
    page = request.args.get("page", '1')
    per_page = request.args.get("per_page", constants.HOME_PAGE_MAX_NEWS)
    category_id = request.args.get("cid", '1')

    try:
        page = int(page)
        per_page = int(per_page)
        category_id = int(category_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=response_code.RET.PARAMERR, errmsg="参数错误")

    args = [category_id == News.category_id] if category_id != 1 else []
    try:
        paginate = News.query.filter(*args).order_by(News.create_time.desc()). \
            paginate(page, per_page, False)
        # 获取查询出来的数据
        items = paginate.items
        total_page = paginate.pages
        current_page = paginate.page
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=response_code.RET.DBERR, errmsg="数据查询失败")

    news_list_dict = [new.to_basic_dict() for new in items]

    return jsonify(errno=response_code.RET.OK, errmsg="OK", totalPage=total_page,
                   currentPage=current_page, newsList=news_list_dict, cid=category_id)
